package com.codc;


import com.struct.Request;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.msgpack.MessagePack;

import java.util.Map;

/**
 * Created by Administrator on 2016/1/7.
 */
public class RequestEncoder extends MessageToByteEncoder<Request> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Request request, ByteBuf sendBuf) throws Exception {
        if (request == null || request.getHeader() == null)
            throw new Exception("The encode message is null");


        sendBuf.writeInt(request.getHeader().getCrcCode()); //校验码, 2个字节
        sendBuf.writeInt((request.getHeader().getLength()));
        sendBuf.writeLong((request.getHeader().getSessionID()));

        byte[] uriBytes = request.getHeader().getUri().getBytes();
        sendBuf.writeInt(uriBytes.length);
        sendBuf.writeBytes(uriBytes);

        MessagePack msgpack = new MessagePack();

        if (request.getBody() != null) {
            byte[] raw = msgpack.write(request.getBody());
            sendBuf.writeBytes(raw);
        }
        else{
            sendBuf.writeByte(0);
        }

        sendBuf.setInt(4, sendBuf.readableBytes() -8);

    }


}
